import React, { Component } from 'react'
import './index.css'

const MyContext = React.createContext()
const { Provider, Consumer } = MyContext
export default class A extends Component {
  state = { userName: 'zxn' }
  render() {
    const { userName } = this.state
    return (
      <div className="a">
        我是A组件 我的用户名是{userName}
        <Provider value={{ userName, age: 18 }}>
          <B />
        </Provider>
      </div>
    )
  }
}

class B extends Component {
  render() {
    return (
      <div className="b">
        我是B组件
        <C />
      </div>
    )
  }
}

class C extends Component {
  static contextType = MyContext
  render() {
    const { userName, age } = this.context
    return (
      <div className="c">
        我是C组件
        <div>
          我从A组件接收到的用户名是{userName}，年龄是{age}
        </div>
        <D />
      </div>
    )
  }
}

function D() {
  return (
    <div className="d">
      我是D组件
      <Consumer>
        {(value) => {
          return (
            <div>
              我从A组件接收到的用户名是{value.userName}，年龄是{value.age}
            </div>
          )
        }}
      </Consumer>
    </div>
  )
}
